import os
from PIL import Image

class Immagine:
    def __init__ (self, path, lun, comp, path_r=""):
        self.lun=lun
        self.path=path
        self.comp=comp
        self.path_r=path_r
    
    def dimensione(self):
        size=os.path.getsize(self.path)
        size=int(size)
        if size < 3145728:
            return 1
        else:
            return 0
        
    def ridimensiona(self):
        size=self.lun, self.lun
        base = os.path.basename(self.path)
        file, ext = os.path.splitext(base)
        img=Image.open(self.path)
        img.thumbnail(size, Image.ANTIALIAS)
        im_rid=self.path_r + os.sep + file + "_rid" + ext
        img.save(im_rid, "JPEG", quality=self.comp)
        return im_rid
    
    def ExifExtractor(self):
        im=Image.open(self.path)
        try:
            exifdb=im._getexif()
        except:
            exifdb={}
        return self.ExifParser(exifdb)
        
    def ExifParser(self, exifdb):
        if exifdb != {} and exifdb != None:
            try:
                f=str(float(exifdb[0x829d][0])/float(exifdb[0x829d][1]))
                if exifdb[0x829a][0] < exifdb[0x829a][1]:
                    t="1/"+ str(exifdb[0x829a][1] / exifdb[0x829a][0])+'"'
                else:
                    t=str(exifdb[0x829a][0]/exifdb[0x829a][1])+'"'
                iso=str(exifdb[0x8827])
                try:
                    lung=str(exifdb[0x920a][0]/exifdb[0x920a][1])+" mm"
                except:
                    lung=""
                camera=exifdb[0x010f]+" "+exifdb[0x0110]
                r1 = camera
                r2 = t + " - F/" + f
                r3 = "ISO " + iso + " - " + lung
                return r1, r2, r3
            except:
                return "ERRORE", "interpretazione EXIF", ""
        else:
            return "ERRORE", "Nessun EXIF", ""